package site.tuluan.sp4j.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;
import site.tuluan.sp4j.common.constant.Constants;
import site.tuluan.sp4j.common.core.domain.entity.SysUserEntity;
import site.tuluan.sp4j.common.utils.security.SecurityUtils;
import site.tuluan.sp4j.module.sys.mapper.SysUserMapper;
import site.tuluan.sp4j.module.sys.service.ISysUserService;

import javax.annotation.Resource;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements ISysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    public SysUserEntity getUser(String account) {
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        return sysUserMapper.selectOne(wrapper);
    }

    public String calcEncryptedPassword(String password, String salt) {
        SimpleHash simpleHash = new SimpleHash(Constants.USER_ENCRYPT_ALGORITHM,
                password, salt, Constants.USER_ENCRYPT_TIMES);
        return simpleHash.toHex();
    }

    public boolean resetPassword(SysUserEntity userEntity) {
        userEntity.setSalt(SecurityUtils.randomSalt());
        userEntity.setPassword(calcEncryptedPassword(userEntity.getPassword(), userEntity.getSalt()));
        return updateById(userEntity);
    }
}
